<!--  -->
<template>
<el-dialog
    v-model="dialogShow"
    :title="model.id == 0 ? '添加' : '修改'"
    width="800"
    :before-close="handleClose"
  >
 {{ model.id }}
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      label-width="auto"
      class="demo-ruleForm"
      :model="model"
      status-icon
      :rules="rules"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="model.name" />
      </el-form-item>
      <el-form-item label="权限" >
        <el-tree
      style="max-width: 600px"
      :data="menus"
      show-checkbox
      node-key="id"
      :default-checked-keys="checkIds"
      default-expand-all
      :expand-on-click-node="false"
      :props="{ label: 'name' }"
      ref="treeRef"
    />


      </el-form-item>
       
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang='ts' setup>
import { reactive,toRefs,ref,onMounted,defineProps,defineEmits} from 'vue'
import type { FormRules,FormInstance } from "element-plus";
import {getRole,addRole} from '../services/role/role'
import {convertToTree} from '../utils/treeUtils'
const props=defineProps(["id"]);
const emits=defineEmits(["close"])
const dialogShow=ref(true);
const ruleFormRef = ref<FormInstance>();
const treeRef=ref<any>();
const rules = reactive<FormRules<any>>({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
});
const menus=ref<any>([]);
const checkIds=ref<Array<number>>([])
const model=reactive<any>({
    id:props.id,
    name:"",
    menus:[]
})
const getTree=async ()=>{
 const res:any=await getRole(model.id);

 console.log(888,res);
 
 if(res.errCode===10000){

  let ids=  res.data.menus.filter((item:any)=>item.checked===1).map((item:any)=>item.id);

  model.name=res.data.name;
//   treeRef.value.setCheckedKeys(ids);


//   setCheckedNodes
  checkIds.value=ids;
  console.log(999,ids);
  
//  let _menus=convertToTree(res.data.menus);

menus.value=convertToTree(res.data.menus);

//  console.log(1111111,_menus);

 }

 
}

onMounted(()=>{
    getTree();
})

const handleClose=()=>{

    emits("close");

}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {

      let rows=  treeRef.value.getCheckedKeys();

      model.menus=rows.map((item:any)=>({id:item}))

     const res:any=await addRole(model);
     if(res.errCode===10000){
        emits("close",true);
     }
     else{
        //提示提交失败
     }

     console.log(res);
     

      console.log(rows);
      
      
    }
  });
};

</script>
<style scoped>
</style>